<?php

namespace App\Http\Controllers\Applet\Cart;

use App\Services\Applet\Cart\CartService;
use Exception;
use Illuminate\Http\JsonResponse;

class CartController extends BaseCartController
{

    protected CartService $cartService;


    /**
     * @throws Exception
     */
    public function __construct()
    {
        parent::__construct();
        $this->cartService = $this->loadService('Applet\Cart\CartService');
    }

    /**
     * 购物车列表
     *
     * @return JsonResponse
     * @throws Exception
     */
    public function list(): JsonResponse
    {
        $rule = [
            'type' => 'required|integer|in:10,20',
        ];

        if ($this->ruleCheck($rule)) {
            return outputJsonError();
        }

        $list = $this->cartService->list($this->params);
        return outputJsonResult($list);
    }

    /**
     * 购物车总数量
     * @return JsonResponse
     * @throws Exception
     */
    public function totalQuantity(): JsonResponse
    {
        $rule = [
            'type' => 'required|integer|in:10,20',
        ];

        if ($this->ruleCheck($rule)) {
            return outputJsonError();
        }

        $data = $this->cartService->totalQuantity($this->params);
        return outputJsonResult($data);
    }

    /**
     * 添加购物车
     *
     * @return JsonResponse
     * @throws Exception
     */
    public function create(): JsonResponse
    {
        $rule = [
            'goodsId' => 'required|integer|min:1',
            'type' => 'required|integer|in:10,20',
            'quantity' => 'required|integer|min:1',
        ];

        if ($this->ruleCheck($rule)) {
            return outputJsonError();
        }

        $this->cartService->create($this->params);

        return outputJsonResult();
    }

    /**
     * 更新购物车
     * @return JsonResponse
     * @throws Exception
     */
    public function update(): JsonResponse
    {
        $rule = [
            'id' => 'required|integer|min:1',
            'quantity' => 'required|integer|min:1',
        ];

        if ($this->ruleCheck($rule)) {
            return outputJsonError();
        }

        $this->cartService->update($this->params);
        return outputJsonResult();
    }

    /**
     * 删除购物车数据
     * @return JsonResponse
     * @throws Exception
     */
    public function delete(): JsonResponse
    {
        $rule = [
            'id' => 'required|integer|min:1',
        ];

        if ($this->ruleCheck($rule)) {
            return outputJsonError();
        }

        $this->cartService->delete($this->params);

        return outputJsonResult();
    }
}
